package Z.dailyExercise._0111;

import java.util.*;

public class _1636_按照频率将数组升序排序 {

    /**
     * 借助treemap key存的是数值 value存频次
     * 实现Collection。sort
     *==28 78
     * @param nums
     * @return
     */
    public int[] frequencySort(int[] nums) {
        Map<Integer,Integer> map = new TreeMap<>();
        for (int num:nums){
            if (!map.containsKey(num)){
                map.put(num,1);
            }else {
                map.put(num,map.get(num)+1);
            }
        }

        List<Map.Entry<Integer,Integer>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                if (o1.getValue() == o2.getValue()){
                    return o2.getKey()-o1.getKey();
                }
                return o1.getValue()-o2.getValue();
            }
        });

        int i=0;
        for (Map.Entry<Integer,Integer> e:list){
            int num = e.getValue();
            while (num>0){
                nums[i]=e.getKey();
                i++;
                num--;
            }
        }

        return nums;


    }
}
